package net.oschina.simpleplus.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.apache.commons.lang3.ClassUtils;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClazzUtil extends ClassUtils {
	
	private static final Logger log = LoggerFactory.getLogger("ClazzUtil");
	
	private static Objenesis objenesis = new ObjenesisStd(true);

	public static void setValue(Object obj, String fieldName, Object... values) throws Exception{
		Class<?> clazz = obj.getClass();
		Field field = null;
		try{
			field = clazz.getDeclaredField(fieldName);
		}catch (Exception e) {
			
			field = clazz.getSuperclass().getDeclaredField(fieldName);
		}
		Method publicMethod = getPublicMethod(clazz, new StringBuilder("set").append(fieldName.substring(0, 1).toUpperCase()).append(fieldName.substring(1)).toString(), field.getType());
		
		publicMethod.invoke(obj, values);
	}
	
	public static <T> T extraData(ResultSet rs, Class<T> clazz) throws SQLException{
		T newInstance = objenesis.newInstance(clazz);
		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();
		for(int i = 1; i <= columnCount; i++){
			String columnName = metaData.getColumnName(i);
			try {
				setValue(newInstance, StrUtil.camelName(columnName), rs.getObject(i));
			} catch (Exception e) {
				log.error("when set value {}", columnName, e);
			}
		}
		return newInstance;
	}
}
